import json
import uuid


class Ops:
    def __init__(self, res):
        self.res = res

    def xpath(self, xpath):
        return self.res.xpath(xpath).extract()

    def strfy(self):
        return str(self.res.body, encoding='utf-8')

    def get_json(self):
        encode = str(self.res.body, encoding='utf-8')
        return json.loads(encode)

    def get_str(self, xpath):
        res = ""
        try:
            res = self.res.xpath(xpath + '/text()')
            res = res.extract()[0].strip()
        except:
            pass

        if not isinstance(res, tuple):
            return res
        else:
            return res[0]

    def get_attr(self, xpath, label):
        res = ""
        try:
            res = self.res.xpath(xpath + '/@' + label).extract()
        except:
            pass
        return ''.join(res)

    def get_num(self, xpath):
        num = 0
        try:
            num = len(self.res.xpath(xpath))
        except:
            pass
        return num

    def get_index(self, xpath, index):
        num = self.get_num(xpath)
        obj = []
        for i in range(num):
            obj.append("[{}]".format(i + 1))
        return self.get_str(xpath + obj[index])

    def save(self, path=str(uuid.uuid1()) + '.html'):
        data = self.res.body
        if not isinstance(data, str):
            data = data.decode("utf-8")
        with open(path, 'w', encoding='utf-8') as f:
            f.write(data)
        print('.....save ok.....')
